import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import My_navbar from "@/components/My_navbar";
import axios from "axios";
import { Button, Input, Result } from "antd-mobile";
type Props = {};

const Loading = () => {
  return (
    <>
      <My_navbar title="还款结果" />
      <Result
        status="waiting"
        title="还款处理中"
        description="内容详情可折行，建议不超过两行建议不超过两行建议不超过两行"
      />
    </>
  );
};

const GotoPay = (props: Props) => {
  const { state } = useLocation();
  const [value, setValue] = useState(state);
  const [show, setShow] = useState(false);

  const Request = axios.create({
    baseURL: "http://localhost:9000",
    timeout: 5000,
  });

  const gotopay = async () => {
    let params = {
      id: Math.random().toString().slice(2, 8),
      price: value,
    };
    let { data } = await Request.get("/pay", { params });
    if (data.code === 200) {
      setShow(true);
      window.open(data.result);
      //   开启轮询
      query(params.id);
    }
  };

  const query = (id: string) => {
    let timer = setInterval(async () => {
      let { data } = await Request.get("/query", { params: { id } });
      if (data.code === 200) {
        clearInterval(timer);
        setShow(false);
        // 跳转结果页
      }
    }, 3000);
  };

  return (
    <div>
      {show ? (
        <Loading />
      ) : (
        <>
          <My_navbar title="提前还款" />
          <Input
            style={{ border: "1px solid #ccc", width: "50vw" }}
            value={value}
            onChange={(e) => setValue(e)}
          />
          <Button block size="large" color="primary" onClick={gotopay}>
            确认还款
          </Button>
        </>
      )}
    </div>
  );
};

export default GotoPay;
